#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "ObjectList.h"
#include "GL/glut.h"
ObjectList::ObjectList()
{
	head = NULL;
	tail = NULL;
}
ObjectList::ObjectList(Object * headObject)
{
	head = new List<Object>(headObject, NULL);
	tail = head;
}
ObjectList::ObjectList(MenuManager * menuManager)
{
	this->menuManager = menuManager;
	head = NULL;
	tail = NULL;
}
ObjectList::ObjectList(MenuManager * menuManager, Object * headObject)
{
	this->menuManager = menuManager;
	head = new List<Object>(headObject, NULL);
	tail = head;
}
ObjectList::~ObjectList()
{
	printf("deleting object list\n");
	List<Object> * search = head;
	while(search)
	{
		search = search->RemoveList();
	}
	head = NULL;
	printf("done deleting objects\n");
}
List<Object> * ObjectList::Add(Object * payload)
{
	head = new List<Object>(payload, head);
	
	if(tail == NULL)
		tail = head;
	return head;
}
void ObjectList::ClearList()
{
	List<Object> * search = head;
	while(search)
	{
		search = search->RemoveList();
	}
	head = NULL;
	tail = NULL;
}

void ObjectList::Remove(Object * point)
{
	List<Object> * search = head;
	while(search)
	{
		if(search->payload && search->payload ==  point)
		{
			if(search == head)
			{
				head = search->next;
			}
			else if(search == tail)
			{
				tail = search->prev;
			}
			search = search->Remove();
			break;
		}
		else
			search = search->next;
	}	
}

void ObjectList::HoverCheck(Mouse * mouse)
{

}
Vertex * ObjectList::GetHoverVertex(Mouse * mouse)
{
	List<Object> * search = head;
	
	while(search)
	{
		if(search->payload)
		{
			Vertex * hoverVertex = NULL;
			hoverVertex = search->payload->GetHover(mouse);
			if(hoverVertex)
				return hoverVertex;
		}
		search = search->next;
	}
	printf("Returning NULL!");
	return NULL;
}
char * ObjectList::GetTags()
{
	List<Object> * search = tail;
	
	int length = 0;
	char * tag = NULL;
	
	while(search)
	{
		if(search->payload)
		{
			char * objectTag = search->payload->GetTag();
			printf("Object Tag = %s\n", objectTag);
			
			tag = (char *)realloc(tag, (length + strlen(objectTag) + 2) * sizeof(char));
			memcpy(tag+length,objectTag, strlen(objectTag)+1);
			int len = strlen(tag);
			tag[len] = '\n';
			tag[len+1]='\0';
			length += strlen(objectTag)+1;
			//delete objectTag;
			
		}
		search = search->prev;
	}
	return tag;
}
void ObjectList::Draw()
{
	List<Object> * search = head;
	
	while(search)
	{
		if(search->payload)
		{
			search->payload->Draw();
		}
		search = search->next;
	}
}
int ObjectList::GetLength()
{
	List<Object> * search = head;
	int i =0;
	while(search)
	{
		i++;
		search = search->next;
	}
	return i;
}

